import axios, { AxiosInstance, AxiosResponse } from "axios";
import router from "../router";

// 创建 axios 实例并声明类型
const service: AxiosInstance = axios.create({
    baseURL: "http://localhost:8848",
    timeout: 5000,
    headers: {
        "Content-Type": "application/json;charset=utf-8"
    }
});

/* eslint-disable */
// 请求拦截器
service.interceptors.request.use((config) => {
    config.headers= config.headers || {};
    if(localStorage.getItem('authentication')){
        config.headers.authentication = localStorage.getItem('authentication') || ""
    }
    return config;
}, (error) => {
    return Promise.reject(error);
});


// 响应拦截器
service.interceptors.response.use(
    (response: AxiosResponse): AxiosResponse => {
        return response;  // 正常响应返回数据
    },
    (error: any) => {
        if (error.response && error.response.status === 401) {  // 处理未授权错误
            const errorMsg = error.response.data?.msg || '登录已过期，请重新登录';
            localStorage.removeItem('authentication');  // 清除无效的 token
            router.push({
                path:'/user/login',
                query:{
                    error: encodeURIComponent(errorMsg)
                }
            });  // 重定向到登录页
        }
        return Promise.reject(error);
    }
);


// 导出 axios 实例
export default service;
